<template>
  <div class="user-management-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="12">
        <el-button
          icon="el-icon-plus"
          type="primary"
          @click="handleEdit($event)"
        >
          添加
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="12">
        <el-form :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.MatchString"
              clearable
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>
    <el-table
      ref="tableSortRef"
      v-loading="listLoading"
      :border="border"
      :data="list"
      :height="height"
      :size="lineHeight"
      :stripe="stripe"
      @selection-change="setSelectRows"
    >
      <el-table-column
        v-for="(item, index) in finallyColumns"
        :key="index"
        align="center"
        :label="item.label"
        :prop="item.prop"
        :sortable="item.sortable"
        width="auto"
      >
        <template slot-scope="scope">
          <el-popover
            v-if="item.label === '适用产品'"
            placement="top-start"
            title="适用产品"
            :width="200"
            trigger="hover"
          >
            <template slot="reference">
              <el-button class="m-2">详情</el-button>
            </template>
            <template slot="default">
              {{ scope.row.ApplyProduct }}
            </template>
          </el-popover>
          <el-popover
            v-else-if="item.label === '适用设备'"
            placement="top-start"
            title="适用设备"
            :width="200"
            trigger="hover"
          >
            <template slot="reference">
              <el-button class="m-2">详情</el-button>
            </template>
            <template slot="default">
              {{ scope.row.ApplyDevice }}
            </template>
          </el-popover>
          <span v-else>{{ scope.row[item.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="left"
        label="操作"
        show-overflow-tooltip
        width="500"
      >
        <template slot-scope="scope">
          <!-- <el-button text type="primary" @click="handleEdit(row)">
            编辑
          </el-button> -->
          <el-button text type="primary" @click="handleEdit(scope.row)">
            程序更新
          </el-button>
          <el-button
            v-if="scope.row.ReleaseState != '已发布'"
            text
            type="primary"
            @click="handleNCRelease(scope.row)"
          >
            发布
          </el-button>
          <el-button text type="primary" @click="handleHistory(scope.row)">
            查看历史版本
          </el-button>
          <el-button text type="danger" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
      <template slot="empty">
        <el-empty class="vab-data-empty" description="暂无数据" />
      </template>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <el-dialog
      :close-on-click-modal="false"
      :visible="dialogVisible"
      :title="title"
      width="50%"
      :before-close="handleClose"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="NC编号">
          <el-input
            v-model="form.Id"
            :rows="2"
            type="text"
            :readonly="type == 'add' ? false : true"
          />
        </el-form-item>
        <el-form-item label="程序名">
          <el-input v-model="form.Name" :rows="2" type="text" readonly />
        </el-form-item>
        <el-form-item label="适用产品">
          <!-- {{ form.ApplyProduct }} -->
          <el-select
            multiple
            v-model="form.ApplyProduct"
            class="m-2"
            placeholder="选择适用产品"
            size="large"
            @change="changeOrder"
            v-if="type == 'add'"
          >
            <el-option
              v-for="item in applyPartData"
              :key="item.ProducationId"
              :label="item.ProducationName"
              :value="item.ProducationName"
            >
              <span style="float: left">{{ item.ProducationName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ item.BluePrintFileId }}
              </span>
            </el-option>
          </el-select>
          <el-input
            v-model="form.ApplyProduct"
            :rows="2"
            type="text"
            readonly
            v-else
          />
        </el-form-item>
        <el-form-item label="适用设备">
          <!-- {{ form.ApplyMachine }} -->
          <el-select
            multiple
            v-model="form.ApplyDevice"
            class="m-2"
            placeholder="选择适用设备"
            size="large"
            @change="changeOrder"
            v-if="type == 'add'"
          >
            <el-option
              v-for="(item, index) in applyMachineData"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
          <el-input
            v-model="form.ApplyDevice"
            :rows="2"
            type="text"
            readonly
            v-else
          />
        </el-form-item>
        <el-form-item label="版本编号">
          <el-input v-model="form.VersionId" :rows="2" type="text" />
        </el-form-item>
        <el-form-item label="版本说明">
          <el-input v-model="form.VersionContent" :rows="2" type="textarea" />
        </el-form-item>
        <el-form-item label="NC文件">
          <!-- <el-input v-model="form.NcPath" :rows="2" type="text" /> -->
          <input type="file" @change="getBase64" />
          <!-- <el-upload
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            :on-change="handleChange"
            :file-list="fileList"
            :limit="1"
            upload
            :before-upload="handleUpload"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload> -->
        </el-form-item>
        <!-- <el-form-item label="操作者">
          <el-input v-model="form.Creator" :rows="2" type="text" />
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker v-model="form.CreateTime" type="date" label="请选择操作时间" placeholder="请选择操作时间"
            style="width: 100%" />
        </el-form-item> -->
      </el-form>
      <template slot="footer">
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :visible="dialogVisible1"
      :before-close="handleClose1"
      title="程序"
      width="50%"
    >
      <div style="height: 300px">
        <el-steps :active="1" direction="vertical">
          <template v-for="item in NCHistoryData">
            <el-step :title="item.VersionId" @click="handleHistory1(item)">
              <template slot="description">
                <div @click="handleHistory1(item)">
                  <div>{{ item.VersionContent }}</div>
                  <div>{{ item.CreateTime }}</div>
                  <div>{{ item.Creator }}</div>
                </div>
              </template>
            </el-step>
          </template>
        </el-steps>
      </div>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      :visible="dialogVisible2"
      title="程序内容"
      width="40%"
    >
      <div style="height: 300px">
        <div>
          <el-input v-model="Content" :rows="3" type="textarea" />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submit2">传输</el-button>
          <el-button type="primary" @click="submit1">回滚版本</el-button>
          <el-button @click="dialogVisible2 = false">取消</el-button>
          <el-button type="primary" @click="submit">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      title="提示"
      :visible.sync="dialogVisible5"
      width="30%"
      :before-close="handleClose5"
    >
      <el-select v-model="DeviceId" placeholder="请选择设备">
        <el-option
          v-for="item in options"
          :key="item"
          :label="item"
          :value="item"
        ></el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible5 = false">取 消</el-button>
        <el-button type="primary" @click="submit6">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    NCList,
    NCInfo,
    NCInfos,
    NCGet,
    NCDelete,
    NCRelease,
    ProductLists,
    DeviceInfo,
    NCVersionFile,
    NCVersionFiles,
    NCVersionRollBack,
    SendNcDeviceList,
    SendNcToDevice,
  } from '@/api/product'
  import { mapGetters } from 'vuex'
  export default {
    data() {
      return {
        DeviceId: '',
        options: [],
        fileList: [],
        form: {
          Id: '',
          Name: '',
          ApplyDevice: [],
          ApplyProduct: [],
          VersionId: '',
          VersionContent: '',
          ReleaseState: '未发布',
          ReleasePeople: null,
          ReleaseTime: null,
          Creator: '',
          CreateTime: '',
          FileContent: '',
        },
        radio: 3,
        formLabelWidth: '100px',
        dialogVisible: false,
        dialogVisible1: false,
        dialogVisible2: false,
        tableSortRef: null,
        editRef: null,
        border: true,
        height: this.$baseTableHeight(1),
        stripe: false,
        lineHeight: 'small',
        isFullscreen: false,
        checkList: [
          '程序编号',
          '程序名称',
          '适用设备',
          '适用产品',
          '文件路径',
          '版本编号',
          '版本说明',
          '创建者',
          '创建时间',
          '发布状态',
          '发布时间',
          '发布人',
        ],
        columns: [
          {
            label: '程序编号',
            prop: 'Id',
            sortable: true,
          },
          {
            label: '程序名称',
            prop: 'Name',
            sortable: true,
          },
          {
            label: '适用设备',
            prop: 'ApplyDevice',
            sortable: true,
          },
          {
            label: '适用产品',
            prop: 'ApplyProduct',
            sortable: true,
          },
          {
            label: '版本编号',
            prop: 'VersionId',
            sortable: true,
          },
          {
            label: '版本说明',
            prop: 'VersionContent',
            sortable: true,
          },
          {
            label: '创建者',
            prop: 'Creator',
            sortable: true,
          },
          {
            label: '创建时间',
            prop: 'CreateTime',
            sortable: true,
          },
          {
            label: '发布状态',
            prop: 'ReleaseState',
            sortable: true,
          },
          {
            label: '发布时间',
            prop: 'ReleaseTime',
            sortable: true,
          },
          {
            label: '发布人',
            prop: 'ReleasePeople',
            sortable: true,
          },
        ],
        list: [],
        imageList: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        queryForm: {
          pageNo: 1,
          pageSize: 10,
          MatchString: '',
        },
        title: '添加',
        applyMachineData: [],
        applyPartData: [],

        NCId: 0,
        NCHistoryData: [],
        type: 'add',
        Content: '',
        dialogVisible5: false,
      }
    },
    computed: {
      ...mapGetters({
        username: 'user/username',
      }),
      finallyColumns() {
        return this.columns.filter((item) =>
          this.checkList.includes(item.label)
        )
      },
    },
    created() {
      this.fetchData()
    },
    methods: {
      handleClose5() {
        this.dialogVisible5 = false
      },
      submit1() {
        const params = {
          NCId: this.NCId,
          VersionId: this.historyInfo.VersionId,
        }
        NCVersionRollBack(params).then((res) => {
          console.log(res)
          this.dialogVisible1 = false
          this.dialogVisible2 = false
          this.fetchData()
        })
      },
      changeOrder() {},
      handleUpload() {},
      getBase64(e) {
        let t = this
        let file = e.target.files[0]
        t.form.Name = file.name
        // 判断文件是否读取完毕，读取完毕后执行
        if (window.FileReader) {
          let reader = new FileReader()
          reader.readAsDataURL(file)
          reader.onload = function (e) {
            let base64String = e.target.result
            // 此处可对该base64进行获取赋值传入后端
            console.log('bese64编码：', base64String)
            t.form.FileContent = base64String
          }
        }
      },
      handleChange(file) {
        return new Promise((resolve, reject) => {
          const fileReader = new FileReader()
          fileReader.readAsDataURL(file.raw) // file 或 raw
          fileReader.onload = (e) => {
            resolve('targettargettarget', fileReader.result)
          }

          fileReader.onerror = () => {
            reject(new Error('文件流异常'))
          }
          console.log('fileReader----', fileReader)
          console.log('resultresult----', fileReader.readyState)
        })
      },
      handleChange1(file) {
        let reader = new FileReader()
        let t = this
        reader.readAsText(file.raw, 'UTF-8') //读取，转换字符编码
        reader.onload = function (e) {
          let val = e.target.result //获取数据
          let rtulist = val.split('\r\n')
          t.form.Name = file.name
          let str = ''
          rtulist.map((v) => {
            str += v
          })
          t.form.FileContent = val
        }
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      submit2() {
        console.log('submit2submit2')
        SendNcDeviceList({ NcId: this.NCId }).then((res) => {
          console.log('res', res)
          this.options = res.DeviceList
          this.dialogVisible5 = true
        })
      },
      submit6() {
        const params = {
          NcId: this.NCId,
          Version: this.VersionId,
          DeviceId: this.DeviceId,
        }
        SendNcToDevice(params).then((res) => {
          this.$baseMessage('提交成功', 'success', 'vab-hey-message-success')
          this.dialogVisible5 = false
          this.fetchData()
        })
      },
      submit() {
        if (this.type == 'add') {
          this.form.ReleasePeople = this.username
          this.form.Creator = this.username
          this.form.CreateTime = this.days()
          this.form.ReleaseTime = this.days()

          const params = {
            NcNewlyModel: this.form,
          }
          NCInfo(params).then((res) => {
            this.$baseMessage('提交成功', 'success', 'vab-hey-message-success')
            this.dialogVisible = false
            this.fetchData()
          })
        } else {
          const params = {
            WebNcReNewlyModel: {
              Id: this.form.Id,
              VersionId: this.form.VersionId,
              VersionContent: this.form.VersionContent,
              FileContent: this.form.FileContent,
            },
          }
          NCInfos(params)
            .then((res) => {
              this.$baseMessage(
                '更新成功',
                'success',
                'vab-hey-message-success'
              )
              this.dialogVisible = false
              this.fileList = []
              this.fetchData()
            })
            .catch((err) => {})
        }
      },
      handleHistory1(item) {
        const params = {
          NCId: this.NCId,
          VersionId: item.VersionId,
        }
        this.VersionId = item.VersionId
        NCVersionFiles(params).then((res) => {
          console.log('NCVersionFiles', res)
          this.Content = res.Content
          this.historyInfo = item
          this.dialogVisible2 = true
        })
      },
      handleEdit(row) {
        const params = {
          Index: 0,
          Count: 100,
        }
        DeviceInfo(params).then((res) => {
          console.log('DeviceInfo', res)
          this.applyMachineData = res.DeviceModelList
        })
        ProductLists(params).then((res) => {
          console.log('ProductLists', res)
          this.applyPartData = res.ProductInfo
        })
        if (row.Id) {
          this.type = 'edit'
          this.title = '编辑'
          this.form = row
        } else {
          this.type = 'add'
          this.title = '添加'
          this.form = {
            Id: '',
            Name: '',
            ApplyDevice: [],
            ApplyProduct: [],
            VersionId: '',
            VersionContent: '',
            ReleaseState: '未发布',
            ReleasePeople: null,
            ReleaseTime: null,
            Creator: '',
            CreateTime: '',
            FileContent: '',
          }
        }

        this.dialogVisible = true
      },
      handleNCRelease(row) {
        const ReleaseTime = this.days()
        const params = {
          NCId: row.Id,
          VersionId: row.VersionId,
          ReleasePeople: this.username,
          ReleaseTime,
        }
        NCRelease(params).then((res) => {
          console.log(res)
          this.fetchData()
        })
      },
      handleHistory(row) {
        console.log('rowrow', row)
        this.NCId = row.Id
        this.dialogVisible1 = true
        NCGet({ NCId: row.Id }).then((res) => {
          this.NCHistoryData = res.VersionInfoList
        })
      },
      handleDelete(row) {
        this.$baseConfirm('你确定要删除当前项吗', null, async () => {
          const { msg } = await NCDelete({
            NCId: row.Id,
          })
          // $baseMessage(msg, 'success', 'vab-hey-message-success')
          await this.fetchData()
        })
        return false
        if (row.id) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await doDelete({ ids: row.id })
            this.$baseMessage(msg, 'success', 'vab-hey-message-success')
            await this.fetchData()
          })
        } else {
          if (this.selectRows.length > 0) {
            const ids = this.selectRows.map((item) => item.id).join()
            this.$baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ ids })
              this.$baseMessage(msg, 'success', 'vab-hey-message-success')
              await this.fetchData()
            })
          } else {
            this.$baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      },
      handleClose() {
        this.dialogVisible = false
      },
      handleClose1() {
        this.dialogVisible1 = false
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNo = val
        this.fetchData()
      },
      queryData() {
        this.queryForm.pageNo = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        const params = {
          Index: this.getPage(this.queryForm.pageNo, this.queryForm.pageSize),
          Count: this.queryForm.pageSize,
          MatchString: this.queryForm.MatchString,
        }
        NCList(params).then((res) => {
          this.list = res.NCManagerModels
          this.list.forEach((item) => {
            item.ApplyProduct = item.ApplyProduct.join(',')
            item.ApplyDevice = item.ApplyDevice.join(',')
            console.log('tiem.ApplyProduct')
          })
          this.total = res.TotalCount
          this.listLoading = false
        })
      },
    },
  }
</script>
